import 'dart:async';
import 'dart:ffi';

import 'package:e_reception_flutter/common_widgets/common_pack_up_keyboard_widget/common_pack_up_keyboard_widget.dart';
import 'package:e_reception_flutter/constants/call_back.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/singleton/user_repository/user_repository.dart';
import 'package:e_reception_flutter/ui/app_main.dart';
import 'package:e_reception_flutter/ui/company/company_detail/event/refresh_company_detail_page_event.dart';
import 'package:e_reception_flutter/ui/company/company_register/widgets/company_register_sms_code_widget.dart';
import 'package:e_reception_flutter/ui/company/company_switch/company_switch_page.dart';
import 'package:e_reception_flutter/ui/login/login_bean/login_search_organization_bean.dart';
import 'package:e_reception_flutter/ui/login/login_index/login_view_model.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/vg_hud_utils.dart';
import 'package:e_reception_flutter/utils/vg_toast_utils.dart';
import 'package:e_reception_flutter/vg_widgets/vg_top_bar_widget/vg_top_bar_widget.dart';
import 'package:flutter/material.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_base_callback.dart';
import 'package:vg_base/vg_evnet_bus_lib.dart';

import 'widgets/login_auth_edit_auth_widget.dart';

/// 验证码验证
///
/// @author: zengxiangxi
/// @createTime: 1/6/21 4:24 PM
/// @specialDemand:
class LoginAuthPage extends StatefulWidget {
  ///路由名称
  static const String ROUTER = "LoginAuthPage";

  final String phone;

  final LoginSearchOrganizationBean beanData1;

  const LoginAuthPage({Key key, this.phone, this.beanData1}) : super(key: key);

  @override
  _LoginAuthPageState createState() => _LoginAuthPageState();

  ///跳转方法
  static Future<dynamic> navigatorPush(BuildContext context, String phone,{LoginSearchOrganizationBean beanData}) {
    return RouterUtils.routeForFutureResult(
      context,
      LoginAuthPage(
        phone: phone,
          beanData1:beanData
      ),
      routeName: LoginAuthPage.ROUTER,
    );
  }
}

class _LoginAuthPageState extends BaseState<LoginAuthPage> {
  StreamController<Null> clearValueNotifier;
  LoginViewModel _viewModel;
  LoginSearchOrganizationBean beanData;
  @override
  void initState() {
    super.initState();
    _viewModel = LoginViewModel(this);
    clearValueNotifier = StreamController();
    _viewModel?.searchOrganization(context, widget?.phone,BaseCallback(onSuccess: (val) {
      LoginSearchOrganizationBean bean = LoginSearchOrganizationBean.fromMap(val);
      beanData = bean;
      setState(() { });
    }, onError: (msg) {
      VgHudUtils.hide(context);
      VgToastUtils.toast(context, msg);
    }));
  }

  @override
  void dispose() {
    clearValueNotifier?.close();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
      body: CommonPackUpKeyboardWidget(child: _toMainColumnWidget()),
    );
  }

  Widget _toMainColumnWidget() {
    return Column(
      children: <Widget>[
        _toTopBarWidget(),
        SizedBox(height: 28),
        _toTitleWidget(),
        SizedBox(height: 30),
        _toTipsWithPhoneWidget(),
        SizedBox(
          height: 30,
        ),
        LoginAuthEditAuthWidget(
          clearValueNotifier: clearValueNotifier,
          loginFunc: (String code) async {
            if(!(beanData?.data?.already??true)&&(beanData?.data?.orgInfoList?.length??0)>0){//already true已导入  false未倒入
              if(beanData?.data?.orgInfoList?.length==1){//查询该账号是否有多个一起学机构/如果只有一个，则走导入接口并登录

                  //倒入机构信息并登录
                  VgHudUtils.show(context, "正在登录");
                  UserRepository.getInstance()
                      .loginService().companyImportOrgLogin(context,widget?.phone, code,beanData?.data?.orgInfoList[0]);
              }else if((beanData?.data?.orgInfoList?.length??0)>1){
                bool result = await CompanySwitchPage.navigatorPush(context,orgInfoList:beanData?.data?.orgInfoList,loginPage: true);
                if (result != null && result) {
                  //切换企业成功
                  VgEventBus.global.send(ChangeCompanyEvent());
                }
              }
            }
            else{
              VgHudUtils.show(context, "正在登录");
              UserRepository.getInstance()
                  .loginService(callback:VgBaseCallback(
                onSuccess: (_) {
                  VgHudUtils.hide(context);
                  VgToastUtils.toast(context, "登录成功");

                },
                onError: (String msg) {
                  VgHudUtils.hide(context);
                  VgToastUtils.toast(context, msg);
                  clearValueNotifier.add(null);
                },
              )).loginByCode(widget?.phone, code);
            }
          },
        ),
        SizedBox(height: 10,),
        CompanyRegisterSmsCodeWidget(
          phoneFunc: ()=> widget?.phone,login: true,
        ),
      ],
    );
  }

  ///topbar
  Widget _toTopBarWidget() {
    return VgTopBarWidget(
      isShowBack: true,
      title: "",
    );
  }

  ///标题
  Widget _toTitleWidget() {
    return Text(
      "输入验证码",
      maxLines: 1,
      overflow: TextOverflow.ellipsis,
      style: TextStyle(
        color: ThemeRepository.getInstance().getTextMainColor_D0E0F7(),
        fontSize: 24,
      ),
    );
  }

  ///已发送至
  Widget _toTipsWithPhoneWidget() {
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: <Widget>[
        Text(
          "已发送至",
          maxLines: 1,
          overflow: TextOverflow.ellipsis,
          style: TextStyle(
            color: ThemeRepository.getInstance().getTextMainColor_D0E0F7(),
            fontSize: 15,
          ),
        ),
        SizedBox(
          width: 8,
        ),
        Text(
          "${widget?.phone ?? ""}",
          maxLines: 1,
          overflow: TextOverflow.ellipsis,
          style: TextStyle(
            color: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
            fontSize: 15,
          ),
        )
      ],
    );
  }
}
